﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BIS.Utility.Converter;
using BIS.Portal.Core.Global;
using BIS.Portal.Modules.CMS.Entity;
using BIS.Portal.Core.Base;
using BIS.Portal.Modules.CMS.BO;
using BIS.Portal.Core.Entity;

namespace BIS.Portal.Modules.CMS.Adm
{
    public partial class AdminCmsArticleUpdateControl : ControlBase
    {
        #region GetDataSetting
        public string CmsArticleInCategory
        {
            get
            {
                return GetControlSetting<string>(
                  ModuleSettingNames.AdminCmsArticleUpdateControl.AdminCmsArticleUpdate_ContentPage, PortalContext.LanguageAlias
                    );
            }
        }
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (hiddenIsPostBack.Value.Equals("false"))
            {
                ValidateData();
            }
        }
        #region ValidateData
        private int ArtcileId
        {
            get
            {
                return Functions.GetInt(Request.QueryString[QueryStringKeys.ArticleId]);
            }
        }
        public void ValidateData()
        {
            string action = Request.QueryString[QueryStringKeys.ArticleUpdateAction];
            if (!string.IsNullOrEmpty(action) && action.Equals("0"))
            {
                // xu ly copy
                btnAddNew.Visible = true;
                btnUpdate.Visible = false;
            }
            BindDataIntoForm();
            BindListOfPageAliasNoiDung();
        }
        #endregion

        #region Bind Data
        private void BindDataIntoDropDownList()
        {
            int languageUseId = 0;
            try
            {
                languageUseId = PortalContext.LanguageInUseId;
            }
            catch (Exception ex)
            {

                Console.Write(ex.Message);
                languageUseId = 1;
            }
            IList<AdminCmsCategoryEntity> list = AdminCmsCategoryBO.GetByLanguageInUseId(languageUseId);
            IList<AdminCmsCategoryEntity> listAdminCategoryEntity = new List<AdminCmsCategoryEntity>();

            AdminListViewUtility.ParseList(0, ref list, ref listAdminCategoryEntity);

            AdminListViewUtility.AddDotList(ref listAdminCategoryEntity);

            radBLCatagoryName.DataSource = listAdminCategoryEntity;
            radBLCatagoryName.DataValueField = "category_id";
            radBLCatagoryName.DataTextField = "category_name";
            radBLCatagoryName.DataBind();

            chkBLCatagoryName.DataSource = listAdminCategoryEntity;
            chkBLCatagoryName.DataValueField = "category_id";
            chkBLCatagoryName.DataTextField = "category_name";
            chkBLCatagoryName.DataBind();


        }
        #region BindPageAlias
        private void BindListOfPageAliasNoiDung()
        {
            Dictionary<string, FullPageSiteEntity> listOfPage = new Dictionary<string, FullPageSiteEntity>();
            PortalContext.GetPageList(0, ref listOfPage, "", false);

            if (listOfPage != null)
            {
                ddlPageAlias.Items.Clear();
                foreach (KeyValuePair<string, FullPageSiteEntity> page in listOfPage)
                {
                    if (page.Value.PageAlias != PortalContext.PageAlias && page.Key != null && page.Value != null)
                    {
                        ddlPageAlias.Items.Add(new ListItem(page.Key, page.Value.PageAlias));
                    }
                }
            }
        }
        #endregion


        public void BindDataIntoForm()
        {
            int temp1;
            BindDataIntoDropDownList();

            AdminCmsArticleEntity list = AdminCmsArticleBO.GetByArticleId(ArtcileId);
            if (list == null)
            {
                return;
            }

            if (ddlPageAlias.Items.FindByValue(list.Page_alias) != null)
            {
                ddlPageAlias.SelectedValue = list.Page_alias;
            }
            //if (list.Page_alias != null)
            //{
            //    ddlPageAlias.SelectedValue = list.Page_alias;
            //}
            //else {
            //    ddlPageAlias.SelectedValue = "0";
            //}
            txtTitle.Text = list.Article_title;
            txtMetaKey.Text = list.Article_meta_keyword;
            txtDescription.Text = list.Article_description;
            txtContent.Text = list.Article_content;
            txtThumbImage.Text = list.Thumb_image;
            txtFullImage.Text = list.Full_image;
            temp1 = list.Is_hot_article;
            if (temp1 == 1)
                chkIsHotArticle.Checked = true;
            else
                chkIsHotArticle.Checked = false;

            ddlLanguage.SelectedValue = list.Language_in_use_id.ToString();

            txtPostDate.Text = list.Post_date.ToString();
            txtPriority.Text = list.Article_priority.ToString();
            //txtStatus.Text = list.Status.ToString();
            ddlStatus.SelectedValue = list.Status.ToString();

            IList<AdminCmsArticleInCategoryEntity> adminCmsArticle = AdminCmsArticleInCategoryBO.GetCategoryId(ArtcileId);

            for (int i = 0; i < adminCmsArticle.Count; i++)
            {
                if (adminCmsArticle != null && adminCmsArticle[i].Category_id > 0)
                {
                    if (adminCmsArticle[i].Is_primary_category == 1)
                    {
                        radBLCatagoryName.SelectedValue = adminCmsArticle[i].Category_id.ToString();
                    }
                    for (int j = 0; j < chkBLCatagoryName.Items.Count; j++)
                    {
                        if (chkBLCatagoryName.Items[j].Value.Equals(adminCmsArticle[i].Category_id.ToString()))
                        {
                            chkBLCatagoryName.Items[j].Selected = true;
                            break;
                        }
                    }
                }
            }
        }
        #endregion

        #region Save Data In Control

        public AdminCmsArticleEntity GetDataForm()
        {
            AdminCmsArticleEntity entity;

            if (ArtcileId == 0)
            {
                entity = new AdminCmsArticleEntity();
            }
            else
            {
                entity = AdminCmsArticleBO.GetByArticleId(ArtcileId);
            }
            if (ddlPageAlias.SelectedValue != null)
            {
                entity.Page_alias = ddlPageAlias.SelectedItem.ToString();
            }
            else
            {
                lblErrorPage.Text = "Không được bỏ trống!!!";
                return null;
            }

            if (!string.IsNullOrEmpty(txtTitle.Text))
            {
                lblErrorTitle.Text = "";
                entity.Article_title = txtTitle.Text;
            }
            else
            {
                lblErrorTitle.Text = "Không được bỏ trống!!!";
                txtTitle.Focus();
            }
            if (!string.IsNullOrEmpty(txtMetaKey.Text))
                entity.Article_meta_keyword = txtMetaKey.Text;
            else
                entity.Article_meta_keyword = "";


            if (!string.IsNullOrEmpty(txtDescription.Text))
                entity.Article_description = txtDescription.Text;
            else
                entity.Article_description = "";
            if (!string.IsNullOrEmpty(txtContent.Text))
            {
                lblErrorContent.Text = "";
                entity.Article_content = txtContent.Text;
            }
            else
            {
                lblErrorContent.Text = "Không được bỏ trống!!!";
                txtContent.Focus();
                return null;
            }

            if (!string.IsNullOrEmpty(txtThumbImage.Text))
                entity.Thumb_image = txtThumbImage.Text;
            else
                entity.Thumb_image = "";

            if (!string.IsNullOrEmpty(txtFullImage.Text))
                entity.Full_image = txtFullImage.Text;
            else
                entity.Full_image = "";

            if (chkIsHotArticle != null)
            {
                if (chkIsHotArticle.Checked)
                    entity.Is_hot_article = 1;
                else
                    entity.Is_hot_article = 0;
            }
            int temps;
            if (ddlLanguage != null)
            {
                int.TryParse(ddlLanguage.SelectedValue, out temps);
                entity.Language_in_use_id = temps;
            }
            if (ddlStatus != null)
            {
                entity.Status = int.Parse(ddlStatus.SelectedValue.ToString());
            }
            if (!string.IsNullOrEmpty(txtPostDate.Text))
            {
                lblErorPostDate.Text = "";
                entity.Post_date = DateTime.Parse(txtPostDate.Text);
            }
            else
            {
                lblErorPostDate.Text = "Hãy nhập ngày tháng";
                txtPostDate.Focus();
            }
            entity.Last_update_by = "System";
            entity.Last_date = DateTime.Parse(DateTime.Now.ToShortDateString());

            return entity;
        }

        #endregion

        #region GetListArticleInCategory
        public List<CategoryInCategoryItem> GetListArticleInCategory()
        {
            List<CategoryInCategoryItem> temp = new List<CategoryInCategoryItem>();

            // Lap trong checkbox
            foreach (ListItem item in chkBLCatagoryName.Items)
            {
                // Neu duoc chon thi add vao List
                if (item.Selected)
                {
                    CategoryInCategoryItem newItem = new CategoryInCategoryItem();
                    newItem.CategoryId = Functions.GetInt(item.Value);
                    newItem.IsPrimaryCategory = 0;

                    temp.Add(newItem);
                }
            }
            // Lay primary category trong danh sach radio
            int primaryCategoryId = Functions.GetInt(radBLCatagoryName.SelectedValue);

            bool primaryCategoryHasBeenFound = false;
            int itemCount = temp.Count;
            // Tim trong danh sach article in category
            for (int i = 0; i < itemCount; i++)
            {
                // Neu tim thay primary category trong danh sach hien tai
                if (temp[i].CategoryId == primaryCategoryId)
                {
                    // Update gias tri IsPrimaryCategory vao item vua tim duoc
                    CategoryInCategoryItem tempItem = temp[i];
                    tempItem.IsPrimaryCategory = 1;
                    temp[i] = tempItem;
                    // Danh dau tim thay primary category trong danh sach hien tai
                    primaryCategoryHasBeenFound = true;
                    break;
                }
            }
            // Neu khong tim thay primary category trong danh sach hien tai
            if (!primaryCategoryHasBeenFound)
            {
                // Them moi category vao danh sach va danh dau la primary category
                CategoryInCategoryItem newItem = new CategoryInCategoryItem();
                newItem.CategoryId = primaryCategoryId;
                newItem.IsPrimaryCategory = 1;
                temp.Add(newItem);
            }

            return temp;
        }
        #endregion

        #region UpdateArticle
        private void UpdateArticle()
        {

            AdminCmsArticleEntity entity = GetDataForm();
            if (entity == null)
            {
                Label1.Text = "Error over here";
                return;
            }
            AdminCmsArticleBO.UpdateArticle(entity);
            AdminCmsArticleInCategoryBO.DeleteData(ArtcileId);
            List<CategoryInCategoryItem> temp = GetListArticleInCategory();
            AdminCmsArticleInCategoryEntity adminCmsArticleInCategoryEntity = null;
            for (int i = 0; i < temp.Count; i++)
            {
                adminCmsArticleInCategoryEntity = new AdminCmsArticleInCategoryEntity()
                {
                    Article_id = ArtcileId,
                    Category_id = temp[i].CategoryId,
                    Is_primary_category = temp[i].IsPrimaryCategory,
                    Article_priority = int.Parse(txtPriority.Text)
                };
                AdminCmsArticleInCategoryBO.InsertData(adminCmsArticleInCategoryEntity);

            }
            string urlLink = WebHelpers.GetLink(UrlRewriteRules.AddArticle, CmsArticleInCategory);
            Response.Redirect(urlLink);
        }
        #endregion

        #region AddArticle
        public void AddArticle()
        {
            AdminCmsArticleEntity bisArticle = GetDataForm();
            if (bisArticle == null)
            {
                Label1.Text = "Error over here";
                return;
            }
            AdminCmsArticleBO.AddArticle(bisArticle);
            List<CategoryInCategoryItem> temp = GetListArticleInCategory();
            AdminCmsArticleInCategoryEntity adminCmsArticleInCategoryEntity = null;
            for (int i = 0; i < temp.Count; i++)
            {
                adminCmsArticleInCategoryEntity = new AdminCmsArticleInCategoryEntity()
                {
                    Article_id = bisArticle.Article_id,
                    Category_id = temp[i].CategoryId,
                    Is_primary_category = temp[i].IsPrimaryCategory,
                    Article_priority = int.Parse(txtPriority.Text)
                };
                AdminCmsArticleInCategoryBO.InsertData(adminCmsArticleInCategoryEntity);
            }
            string urlLink = WebHelpers.GetLink(UrlRewriteRules.AddArticle, CmsArticleInCategory);
            Response.Redirect(urlLink);
        }
        #endregion

        #region Action method
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            UpdateArticle();
        }

        protected void btnAddNew_Click(object sender, EventArgs e)
        {
            AddArticle();

        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            string urlLink = WebHelpers.GetLink(UrlRewriteRules.AddArticle, CmsArticleInCategory);
            Response.Redirect(urlLink);
        }

        #endregion
        protected string FTPFileManagmentURL
        {
            get
            {
                try
                {
                    return "/FileManagement/AdminCateIntegratedPopupWindow.aspx";//GetControlSetting<string>(
                    //         ModuleSettingNames.AdminCmsArticleUpdateControl.AdminCmsArticleUpdate_ContentPage, PortalContext.LanguageAlias);
                }
                catch (Exception ex)
                {
                    Console.Write(ex.Message);

                    return "";
                }
            }
        }
    }
    public class CategoryInCategoryItem
    {
        public int CategoryId;
        public int IsPrimaryCategory;
    }
}